package com.flower.enjoyment.flower.controller;

import com.alibaba.fastjson.JSONObject;
import com.flower.enjoyment.flower.base.ResultMsg;
import com.flower.enjoyment.flower.entityDo.ShopInfoDo;
import com.flower.enjoyment.flower.entityDo.SysBannerDo;
import com.flower.enjoyment.flower.entityDo.UserAssessDo;
import com.flower.enjoyment.flower.enumUtils.ResultEnum;
import com.flower.enjoyment.flower.service.ShopService;
import com.flower.enjoyment.flower.service.SysBannerService;
import com.flower.enjoyment.flower.service.UserAssessService;
import com.flower.enjoyment.flower.utils.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.List;

@RestController
@RequestMapping("/homeApi")
@Api(value = "首页信息",description = "首页信息")
public class HomeController {

    @Autowired
    private SysBannerService sysBannerService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private UserAssessService userAssessService;


    @ApiOperation(value="首页banner", notes="首页banner")
    @ResponseBody
    @GetMapping("/bannerHomeList")
    public ResultMsg<SysBannerDo> getBannerList(){
        List<SysBannerDo> bannerDoList = sysBannerService.getBannerList(1);
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),bannerDoList);
    }
    @ApiOperation(value="邀请好有banner", notes="邀请好有banner")
    @ResponseBody
    @GetMapping("/friendBanner")
    public ResultMsg<SysBannerDo> friendBanner(){
        List<SysBannerDo> bannerDoList = sysBannerService.getBannerList(2);
        SysBannerDo sysBannerDo = null;
        if (bannerDoList.size()>0)
            sysBannerDo=bannerDoList.get(0);
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),sysBannerDo);
    }

    @ApiOperation(value="推荐门店", notes="推荐门店")
    @ResponseBody
    @GetMapping("/commendHomeShopList")
    public ResultMsg<ShopInfoDo> getCommendShopList(){
        List<ShopInfoDo> shopInfoDoList = shopService.getCommendShopHomeList();


        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(), shopInfoDoList);
    }

    @ApiOperation(value="魅力秀", notes="魅力秀")
    @ResponseBody
    @GetMapping("/assessHomeList")
    public ResultMsg<UserAssessDo> getAssessHomeList(@ApiParam(value = "用户ID") @RequestParam( value = "userId") String userId){
        List<UserAssessDo> userAssessDoList = userAssessService.selectUserAssessListByHome(userId);
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),userAssessDoList);
    }

    @ApiOperation(value="评价详情", notes="评价详情")
    @ResponseBody
    @GetMapping("/assessDetailById")
    public ResultMsg<UserAssessDo> getAssessDetail(@ApiParam(value = "评价ID") @RequestParam( value = "assessId", required = true) String assessId ){
        UserAssessDo userAssessDo = userAssessService.selectByPrimaryKey(assessId);
        return new ResultMsg(ResultEnum.SUCCESS_CODE.getCode(),userAssessDo);
    }

    @RequestMapping(value = "/callbackInfo")
    @ResponseBody
    public void ipn(HttpServletRequest request, HttpServletResponse response) {
/*


        //获取参数名称
        Enumeration<String> requestParams = request.getParameterNames();
        //遍历获取参数
        JSONObject jsonObject = new JSONObject();
        while (requestParams.hasMoreElements()) {
            String param = requestParams.nextElement();
            String value = request.getParameter(param);
            jsonObject.put(param,value);

            System.out.println("ipn回调-----"+param+":"+value);
        }*/
        //HttpUtil.doPostJson("http://8.129.213.90:8085/order/callback",jsonObject.toJSONString());
       try {
           Enumeration en = request.getParameterNames();
           String str = "cmd=_notify-validate";
           while (en.hasMoreElements()) {
               String paramName = (String) en.nextElement();
               String paramValue = request.getParameter(paramName);
               str = str + "&" + paramName + "="
                       + URLEncoder.encode(paramValue, "utf-8");
               //此处的编码一定要和自己的网站编码一致，不然会出现乱码，paypal回复的通知为‘INVALID’
           }
           System.out.println("paypal传递过来的交易信息:" + str);
           //建议在此将接受到的信息 str 记录到日志文件中以确认是否收到 IPN 信息
           //将信息 POST 回给 PayPal 进行验证
           //设置 HTTP 的头信息
           //在 Sandbox 情况下，设置：
           URL u = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
           //正式环境
           //      URL u = new URL("https://www.paypal.com/cgi-bin/webscr");
           URLConnection uc = u.openConnection();
           uc.setDoOutput(true);
           uc.setRequestProperty("Content-Type",
                   "application/x-www-form-urlencoded");
           PrintWriter pw = new PrintWriter(uc.getOutputStream());
           pw.println(str);
           pw.close();
           //接受 PayPal 对 IPN 回发的回复信息
           BufferedReader in = new BufferedReader(new InputStreamReader(
                   uc.getInputStream()));
           String res = in.readLine();
           in.close();

           /* String itemName = request.getParameter("item_name");//商品名
            String itemNumber = request.getParameter("item_number");//购买数量
            String paymentStatus = request.getParameter("payment_status");//交易状态
            String paymentDate = request.getParameter("payment_date");//交易时间
            String paymentAmount = request.getParameter("mc_gross");//交易钱数
            String paymentCurrency = request.getParameter("mc_currency");//货币种类
            String txnId = request.getParameter("txn_id");//交易id
            String receiverEmail = request.getParameter("receiver_email");//收款人email
            String payerEmail = request.getParameter("payer_email");//付款人email
*/
           //获取参数名称
           Enumeration<String> requestParams = request.getParameterNames();
           //遍历获取参数
           JSONObject jsonObject = new JSONObject();
           while (requestParams.hasMoreElements()) {
               String param = requestParams.nextElement();
               String value = request.getParameter(param);
               jsonObject.put(param,value);

               System.out.println("ipn回调-----"+param+":"+value);
           }

           System.out.println(res+"paypal回调信息："+jsonObject.toString());

           if (res == null || res == "")
               res = "0";
           //…
           //获取 PayPal 对回发信息的回复信息，判断刚才的通知是否为 PayPal 发出的
           if (res.equals("VERIFIED")) {
               //检查付款状态
               if("Completed".equals(jsonObject.getString("payment_status"))){
                   //检查 txn_id 是否已经处理过

                   String result = HttpUtil.doPostJson("http://8.129.213.90:8085/order/getProductById/"+jsonObject.getLong("custom"),"");
                   if (result==null){
                       //返回异常
                       response.setStatus(500);
                       response.getWriter().append("server error");

                   }
                   System.out.println("返回信息："+result);
                   int rest = Integer.parseInt(result);
                   if (rest==0 || rest==4 || rest==5 || rest==6){
                       //修改订单信息
                       result = HttpUtil.doPostJson("http://8.129.213.90:8085/order/callbacktt",jsonObject.toJSONString());

                   }
               }
               //检查 receiver_email 是否是您的 PayPal 账户中的 EMAIL 地址
               //检查付款金额和货币单位是否正确
               //处理其他数据，包括写数据库

           } else if (res.equals("INVALID")) {
               //非法信息，可以将此记录到您的日志文件中以备调查
               System.out.println("PayPal非法请求："+jsonObject.toJSONString());
               //返回异常
               response.setStatus(500);
               response.getWriter().append("server error");
           } else {
               //处理其他错误
               System.out.println("PayPal其他错误："+jsonObject.toJSONString());
               //返回异常
               response.setStatus(500);
               response.getWriter().append("server error");
           }

       }catch (Exception e){
           e.printStackTrace();
       }
    }
    @RequestMapping(value = "/callbackInfo2")
    @ResponseBody
    public void ipn2(@RequestBody  JSONObject jsonObject) {
        System.out.println("ipn回调-----"+jsonObject.toJSONString());
        HttpUtil.doPostJson("http://8.129.213.90:8085/order/callback",jsonObject.toJSONString());

    }

}
